"""
主窗口模块
"""
import os
import sys
from PyQt6.QtWidgets import (
    QMainWindow, QApplication, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QLabel, QFileDialog, QProgressBar, QTextEdit,
    QTableView, QLineEdit, QComboBox, QGroupBox, QMessageBox
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal
import pandas as pd
from ..core.parser import CrashStackParser
from ..core.file_handler import FileHandler
from ..utils.logger import global_logger


class ParserWorker(QThread):
    """解析工作线程"""
    progress_updated = pyqtSignal(int)
    parsing_completed = pyqtSignal(object)
    error_occurred = pyqtSignal(str)
    
    def __init__(self, dsym_path, input_file):
        super().__init__()
        self.dsym_path = dsym_path
        self.input_file = input_file
    
    def run(self):
        try:
            # 创建解析器并解析文件
            parser = CrashStackParser(self.dsym_path)
            result_df = parser.parse_file(self.input_file, self.update_progress)
            self.parsing_completed.emit(result_df)
        except Exception as e:
            self.error_occurred.emit(str(e))
    
    def update_progress(self, value):
        """更新进度信号"""
        self.progress_updated.emit(int(value))


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("iOS崩溃堆栈解析工具")
        self.setMinimumSize(800, 600)
        
        # 初始化变量
        self.input_file_path = ""
        self.dsym_file_path = ""
        self.output_file_path = ""
        self.result_df = None
        
        # 设置中心部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # 创建主布局
        self.main_layout = QVBoxLayout(self.central_widget)
        
        # 创建UI组件
        self.create_file_selection_section()
        self.create_dsym_selection_section()
        self.create_output_section()
        self.create_progress_section()
        self.create_log_section()
        self.create_action_section()
        
        # 记录启动信息
        global_logger.info("iOS崩溃堆栈解析工具启动")
    
    def create_file_selection_section(self):
        """创建文件选择区域"""
        group_box = QGroupBox("选择崩溃堆栈文件")
        layout = QHBoxLayout()
        
        self.file_path_edit = QLineEdit()
        self.file_path_edit.setReadOnly(True)
        self.file_path_edit.setPlaceholderText("请选择崩溃堆栈文件（CSV或TXT格式）")
        
        browse_button = QPushButton("浏览...")
        browse_button.clicked.connect(self.browse_input_file)
        
        layout.addWidget(self.file_path_edit)
        layout.addWidget(browse_button)
        
        group_box.setLayout(layout)
        self.main_layout.addWidget(group_box)
    
    def create_dsym_selection_section(self):
        """创建dSYM选择区域"""
        group_box = QGroupBox("选择dSYM文件")
        layout = QHBoxLayout()
        
        self.dsym_path_edit = QLineEdit()
        self.dsym_path_edit.setReadOnly(True)
        self.dsym_path_edit.setPlaceholderText("请选择dSYM文件或目录")
        
        browse_button = QPushButton("浏览...")
        browse_button.clicked.connect(self.browse_dsym_file)
        
        layout.addWidget(self.dsym_path_edit)
        layout.addWidget(browse_button)
        
        group_box.setLayout(layout)
        self.main_layout.addWidget(group_box)
    
    def create_output_section(self):
        """创建输出选项区域"""
        group_box = QGroupBox("导出选项")
        layout = QHBoxLayout()
        
        output_label = QLabel("输出文件名:")
        self.output_file_edit = QLineEdit("crash_parsed_result")
        
        format_label = QLabel("导出格式:")
        self.format_combo = QComboBox()
        self.format_combo.addItems(["CSV", "TXT"])
        
        browse_button = QPushButton("选择目录...")
        browse_button.clicked.connect(self.browse_output_dir)
        
        layout.addWidget(output_label)
        layout.addWidget(self.output_file_edit)
        layout.addWidget(format_label)
        layout.addWidget(self.format_combo)
        layout.addWidget(browse_button)
        
        group_box.setLayout(layout)
        self.main_layout.addWidget(group_box)
    
    def create_progress_section(self):
        """创建进度区域"""
        group_box = QGroupBox("解析进度")
        layout = QVBoxLayout()
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        
        layout.addWidget(self.progress_bar)
        
        group_box.setLayout(layout)
        self.main_layout.addWidget(group_box)
    
    def create_log_section(self):
        """创建日志区域"""
        group_box = QGroupBox("日志信息")
        layout = QVBoxLayout()
        
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        
        layout.addWidget(self.log_text)
        
        group_box.setLayout(layout)
        self.main_layout.addWidget(group_box)
    
    def create_action_section(self):
        """创建操作按钮区域"""
        layout = QHBoxLayout()
        
        self.parse_button = QPushButton("开始解析")
        self.parse_button.clicked.connect(self.start_parsing)
        
        self.export_button = QPushButton("导出结果")
        self.export_button.clicked.connect(self.export_results)
        self.export_button.setEnabled(False)
        
        layout.addWidget(self.parse_button)
        layout.addWidget(self.export_button)
        
        self.main_layout.addLayout(layout)
    
    def browse_input_file(self):
        """选择输入文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择崩溃堆栈文件",
            "",
            "支持的文件 (*.csv *.txt);;CSV文件 (*.csv);;文本文件 (*.txt);;所有文件 (*)"
        )
        
        if file_path:
            self.input_file_path = file_path
            self.file_path_edit.setText(file_path)
            self.log_message(f"已选择输入文件: {file_path}")
            
            # 检查文件格式
            if not FileHandler.is_supported_format(file_path):
                self.log_message("警告: 不支持的文件格式", "warning")
    
    def browse_dsym_file(self):
        """选择dSYM文件"""
        dsym_path = QFileDialog.getExistingDirectory(
            self,
            "选择dSYM文件或目录",
            ""
        )
        
        if dsym_path:
            self.dsym_file_path = dsym_path
            self.dsym_path_edit.setText(dsym_path)
            self.log_message(f"已选择dSYM路径: {dsym_path}")
    
    def browse_output_dir(self):
        """选择输出目录"""
        output_dir = QFileDialog.getExistingDirectory(
            self,
            "选择输出目录",
            ""
        )
        
        if output_dir:
            # 更新输出文件名，保留用户输入的文件名部分
            file_name = self.output_file_edit.text()
            if not file_name:
                file_name = "crash_parsed_result"
            
            # 根据选择的格式确定文件扩展名
            ext = ".csv" if self.format_combo.currentText() == "CSV" else ".txt"
            
            self.output_file_path = os.path.join(output_dir, file_name + ext)
            self.log_message(f"已选择输出路径: {self.output_file_path}")
    
    def start_parsing(self):
        """开始解析操作"""
        # 验证输入
        if not self.input_file_path:
            self.show_error("请先选择输入文件")
            return
        
        if not self.dsym_file_path:
            self.show_error("请先选择dSYM文件或目录")
            return
        
        # 禁用按钮防止重复操作
        self.parse_button.setEnabled(False)
        self.progress_bar.setValue(0)
        
        # 创建并启动工作线程
        self.worker = ParserWorker(self.dsym_file_path, self.input_file_path)
        self.worker.progress_updated.connect(self.update_progress)
        self.worker.parsing_completed.connect(self.parsing_completed)
        self.worker.error_occurred.connect(self.handle_error)
        
        self.log_message("开始解析崩溃堆栈...")
        self.worker.start()
    
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(value)
    
    def parsing_completed(self, result_df):
        """解析完成处理"""
        self.result_df = result_df
        self.log_message(f"解析完成，共处理 {len(result_df)} 行数据")
        
        # 启用导出按钮
        self.export_button.setEnabled(True)
        self.parse_button.setEnabled(True)
        
        # 如果没有选择输出路径，设置默认路径
        if not self.output_file_path:
            ext = ".csv" if self.format_combo.currentText() == "CSV" else ".txt"
            default_name = "crash_parsed_result" + ext
            self.output_file_path = os.path.join(os.path.dirname(self.input_file_path), default_name)
    
    def export_results(self):
        """导出解析结果"""
        if self.result_df is None:
            self.show_error("没有可导出的结果")
            return
        
        # 如果没有设置输出路径，提示用户选择
        if not self.output_file_path:
            self.browse_output_dir()
            if not self.output_file_path:
                return
        
        # 确定导出格式
        format_type = self.format_combo.currentText().lower()
        
        try:
            # 导出文件
            output_path = FileHandler.export_results(
                self.result_df,
                self.output_file_path,
                format_type
            )
            
            self.log_message(f"结果已导出到: {output_path}")
            
            # 询问是否打开输出目录
            reply = QMessageBox.question(
                self,
                "导出成功",
                f"结果已导出到: {output_path}\n是否打开所在文件夹?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.Yes
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                # 打开输出文件所在目录
                output_dir = os.path.dirname(output_path)
                if sys.platform == 'darwin':  # macOS
                    os.system(f"open '{output_dir}'")
                elif sys.platform == 'win32':  # Windows
                    os.system(f'explorer "{output_dir}"')
                else:  # Linux
                    os.system(f'xdg-open "{output_dir}"')
        
        except Exception as e:
            self.show_error(f"导出失败: {str(e)}")
    
    def handle_error(self, error_msg):
        """处理错误"""
        self.log_message(f"错误: {error_msg}", "error")
        self.show_error(error_msg)
        self.parse_button.setEnabled(True)
    
    def log_message(self, message, level="info"):
        """添加日志消息"""
        # 添加到GUI日志区域
        self.log_text.append(message)
        
        # 添加到日志文件
        if level == "info":
            global_logger.info(message)
        elif level == "warning":
            global_logger.warning(message)
        elif level == "error":
            global_logger.error(message)
    
    def show_error(self, message):
        """显示错误对话框"""
        QMessageBox.critical(self, "错误", message)


def run_app():
    """启动应用程序"""
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec()) 